import { V, Connection } from 'x-engine';
import { Response } from 'express';
import * as fs from 'fs';
import { ProxyUser } from '../ml/proxy_user';
import { COrderStatus, caipiao } from '../../../collect';
import { strtotime, date } from 'locutus/php/datetime';
import { X, FindOption } from 'x-orm';
import { VrOrder } from '../ml/order';

import xlsx from 'node-xlsx';

const goods50 = 232;
const goods100 = 233;

@V.Controller({
    type: Connection.HTTP,
    url: "/proxy/download/:method",
    authorization: ['proxy']
})
export class DownloadService {
    /**
       * 得到直属下级会员
       */
    async _getChildren(proxyUser: ProxyUser) {
        await X.makeAddon(proxyUser, 'children');
        return proxyUser.children;
    }

    /**
     * 得到所有下级会员
     */
    async _getAllChildren(proxyUser: ProxyUser, includeSelf = false) {
        let children = await this._getChildren(proxyUser);
        let result = children;
        for (let i = 0; i < children.length; i++) {
            result = result.concat(await this._getAllChildren(children[i]));
        }
        return result;
    }


    async order_list(
        proxyUser: ProxyUser,
        res: Response,

        phone?,
        start_time?,
        end_time?,
        winType?,
        status?,
        parent_id?,
    ) {
        /**检索条件，可能会更改 */
        const children = await this._getAllChildren(proxyUser);
        children.push(proxyUser);

        const option: FindOption<VrOrder> = {
            where: {
                from_proxy: {
                    in: children.map(item => item.id)
                },
                order_state: {
                    gt: 10
                }
            },
            addon: {
                proxy_member: true,
                proxy_parent: true,
            }
        }

        if (!start_time) {
            start_time = '1970-01-01';
        }
        if (!end_time) {
            end_time = '2099-01-01';
        }
        option.where.add_time = {
            let: strtotime(end_time),
            get: strtotime(start_time)
        };
        //手机号
        if (phone) {
            option.where.buyer_phone = phone;
        }
        //所属
        if (parent_id) {
            option.where.from_proxy = parent_id;
        }
        //胜负
        if (winType == 'win') {
            option.where.caipiao_status = { get: COrderStatus.win };
        }
        else if (winType == 'lose') {
            option.where.caipiao_status = COrderStatus.lose
        }
        else {
            option.where.caipiao_status = {
                get: COrderStatus.notopen
            }
        }
        if (status == 'gotten') {
            option.where.and = {
                caipiao_status: COrderStatus.gotten
            }
        }
        /**end */

        const list = await X.of(VrOrder).find(option);
        let data = [];
        //header
        data.push("订单号	手机号	昵称	直属机构	交易时间	彩票类型	彩票期数	商品名称	竞购价	购买方向	购货量	货款总额	客户手续费	服务费	留存手续费	状态	胜负	开奖结果".split(/\s+/));
        let _list = await Promise.all(list.map(async item => {
            let getStatus = () => {
                if (item.caipiao_status == COrderStatus.gotten) {
                    return '已领取'
                }
                if (item.caipiao_status == COrderStatus.saled) {
                    return '已转卖'
                }
                else {
                    return '已支付';
                }
            };
            const getWin = () => {
                if (item.caipiao_status == COrderStatus.lose) {
                    return '负';
                }
                else if (item.caipiao_status >= COrderStatus.win) {
                    return '胜';
                }
                else {
                    return '未开奖';
                }
            }
            const getResult = () => {
                let r = getWin();
                if (r == '胜') {
                    return single;
                }
                else if (r == '负') {
                    return -single;
                }
                else {
                    return 0;
                }
            }
            let single = (item.order_amount - item.s_fee - item.f_fee) / item.goods_num;
            return [
                item.order_sn + "",
                item.buyer_phone,
                item.proxy_member.nickname,
                item.proxy_parent.nickname,
                date("Y-m-d H:i:s", item.add_time),
                "时时彩",
                item.term,
                item.goods_name,
                (item.order_amount - item.s_fee - item.f_fee) / item.goods_num,
                item.guess == 'single' ? "单" : "双",
                item.goods_num,
                item.order_amount,
                item.s_fee + item.f_fee,
                item.f_fee,
                item.s_fee,
                //状态
                getStatus(),
                //胜负
                getWin(),
                //开奖结果
                getResult()
            ]
        }))
        data = data.concat(_list);

        var buffer = xlsx.build([{ name: "mySheetName", data: data }]);

        res.set({
            "content-type": 'application/octet-stream',
            "Content-Disposition": "attachment; filename=order.xlsx"
        })
        // let buf = new Buffer("cubi");
        res.send(buffer);
        // fs.writeFileSync("chishi.txt",buf);
        // res.download('chishi.txt',function(){
        //     console.log("success");
        // });
        res.end();
        // fs.createReadStream("chishi.txt").pipe(res)
        // let stream = fs.createWriteStream('chishi.txt');
        // stream.pipe(res).write(buf)
        // fs.createWriteStream('chishi.txt').write(buf).pipe(res)
        // res.send(buf);
        // res.end();
    }

    /**
     * 成交报表
     */
    async chengjiao(
        proxyUser: ProxyUser,
        res: Response,
        type?,
        start_time?,
        end_time?
    ) {
        if (!type) {
            return;
        }
        let today = strtotime(date("Y-m-d"));
        switch (type) {
            case 'yestoday':
                end_time = today;
                start_time = today - 24 * 3600;
                break;

            case 'last7days':
                end_time = today;
                start_time = today = 7 * 24 * 3600;
                break;

            case 'last15days':
                end_time = today;
                start_time = today - 15 * 24 * 3600;
                break;

            case 'lastmonth':
                end_time = today;
                start_time = today - 30 * 24 * 3600;
                break;

            case 'custom':
                end_time = strtotime(end_time);
                start_time = strtotime(start_time);
                break;
        }
        let list = await X.of(VrOrder).find({
            where: {
                add_time: {
                    let: end_time,
                    get: start_time,
                },
                order_state: {
                    get: 20
                },
                caipiao_status: {
                    get: COrderStatus.notopen
                },
                from_proxy: {
                    gt: 0
                }
            },
            addon: {
                proxy_member: true,
                proxy_parent: 1,
                proxy_margin: 1
            }
        });

        //按固定日期及手机号统计
        let cache: any = {};
        await Promise.all(list.map(async item => {
            const time = date("Ymd", item.add_time);
            const index = time + item.goods_id + item.buyer_phone + item.from_proxy;
            let target = cache[index] = cache[index] || {
                total_goods_num: 0,
                total_order_num: 0,
                total_amount: 0,
                time: time,
                goods_name: item.goods_name,
                win_rate: 0,
                win_order: 0,
                nickname: item.proxy_member.nickname,
                phone: item.buyer_phone,
                shouxufei: 0,
                left: 0,
                from_normal: null,
                from_jigou: null,
                from_jujian: null,
                from_jingji: null,
                normal_money: 0,
                jingji_money: 0,
                jujian_money: 0,
                jigou_money: 0,
                result : 0
            };
            //第一次
            if (target.total_order_num == 0) {
                do {
                    if (!item.proxy_margin) {
                        break;
                    }
                    if (item.proxy_margin.normal_id > 0) {
                        let p = await X.of(ProxyUser).findOne(item.proxy_margin.normal_id);
                        if (p) {
                            target.from_normal = p.nickname;
                        }
                    }
                    if (item.proxy_margin.jingji_id > 0) {
                        let p = await X.of(ProxyUser).findOne(item.proxy_margin.jingji_id);
                        if (p) {
                            target.from_jingji = p.nickname;
                        }
                    }
                    if (item.proxy_margin.jigou_id > 0) {
                        let p = await X.of(ProxyUser).findOne(item.proxy_margin.jigou_id);
                        if (p) {
                            target.from_jigou = p.nickname;
                        }
                    }
                    if (item.proxy_margin.jujian_id > 0) {
                        let p = await X.of(ProxyUser).findOne(item.proxy_margin.jujian_id);
                        if (p) {
                            target.from_jujian = p.nickname;
                        }
                    }
                } while (0);
            }

            target.total_goods_num += item.goods_num;
            target.total_order_num += 1;
            target.total_amount += item.order_amount;
            if (item.caipiao_status > COrderStatus.lose) {
                target.win_order += 1;
            }
            target.win_rate = Math.floor(target.win_order / target.total_order_num);
            target.shouxufei += item.f_fee + item.s_fee;

            if (item.proxy_margin) {
                target.normal_money += item.proxy_margin.normal_money;
            }
            if (item.proxy_margin) {
                target.jingji_money += item.proxy_margin.jingji_money;
            } 
            if (item.proxy_margin) {
                target.jigou_money += item.proxy_margin.jigou_money;
            } 
            if (item.proxy_margin) {
                target.jujian_money += item.proxy_margin.jujian_money;
            }
            //开奖结果
            if(item.caipiao_status == COrderStatus.lose){
                target.result -= (item.order_amount - item.f_fee - item.s_fee)
            }
            else if(item.caipiao_status > COrderStatus.lose){
                target.result += (item.order_amount - item.f_fee - item.s_fee);
            }
        }));

        console.log(cache)


        let data = [];
        data.push(`结算日期	面值	所属综合会员	所属经济会员	所属机构代理	所属居间代理	客户手机号	客户昵称	总定货量	成交笔数	胜利次数	胜率	货款总额	开奖结果	定货手续费	留存手续费	经纪会员手续费返佣	机构代理手续费返佣	居间代理手续费返佣
        `.split(/\s+/));
        for (let item of Object.values(cache)) {
            //找爹

            data.push([
                item.time,
                item.goods_name,
                item.from_normal || '',
                item.from_jingji || '',
                item.from_jigou || '',
                item.from_jujian || '',
                item.phone,
                item.nickname,
                item.total_goods_num,
                item.total_order_num,
                item.win_order,
                item.win_rate,
                item.total_amount,
                item.result,
                item.shouxufei,
                item.normal_money,
                item.jingji_money,
                item.jigou_money,
                item.jujian_money
                // item.left,
            ])
        }


        var buffer = xlsx.build([{ name: "mySheetName", data: data }]);

        res.set({
            "content-type": 'application/octet-stream',
            "Content-Disposition": "attachment; filename=exchange.xlsx"
        });
        res.send(buffer);
        res.end();

        // console.log(123)

    }
}